package reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reggie.common.R;
import reggie.entity.User;
import reggie.service.UserService;
import reggie.utils.SMSUtils;
import reggie.utils.SendSms;
import reggie.utils.ValidateCodeUtils;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user) throws Exception {

        //获取手机号
        String phone = user.getPhone();

        //判断手机号是否为空
        if (StringUtils.isNotEmpty(phone)) {

            //生成手机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
//            String code = ValidateCodeUtils.generateValidateCodeString(4);
            log.info("验证码：{}",code);

            //调用阿里云API
//            SMSUtils.sendMessage(phone,code);
            SendSms.sendmsg(phone,code);

            //将验证码存入redis
            redisTemplate.opsForValue().set(phone,code);

            log.info("验证码：{}",redisTemplate.opsForValue().get(phone));
            return R.success("短信验证成功！");
        }
        return R.error("短信验证失败！");
    }

    /**
     * 用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public  R<User> login(@RequestBody Map map, HttpSession session) {
        //获取手机号
        String phone = map.get("phone").toString();
        
        //获取验证码
        String code = map.get("code").toString();

        //获取session中的验证码
//        String codeInSession = session.getAttribute(phone).toString();

        //获取redis中的验证码
        String codeInSession = (String) redisTemplate.opsForValue().get(phone);
        System.out.println(codeInSession);

        //比较用户输入的验证码和session中的验证码
        if (codeInSession != null && code.equals(codeInSession)) {
            //一样则登陆成功
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(queryWrapper);

            //判断是否为新用户，新用户则自动注册保存信息
            if (user ==null) {
                //如果为空则为新用户，保存信息
                user = new User();
                user.setPhone(phone);

                userService.save(user);
            }

            session.setAttribute("user",user.getId());

            //如果登录成功，则删除验证码
            redisTemplate.delete(phone);

            return R.success(user);
        }
        return R.error("登录失败！");
    }
}
